<template>
  <div class="user-manage">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>用户管理</h2>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索用户"
              class="search-input"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              添加用户
            </el-button>
          </div>
        </div>
      </template>

      <!-- 用户列表 -->
      <el-table
        v-loading="loading"
        :data="userList"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="40" :src="row.avatar" />
              <div class="user-detail">
                <div class="username">{{ row.username }}</div>
                <div class="email">{{ row.email }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'admin' ? 'danger' : 'success'">
              {{ row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="180" />
        <el-table-column prop="lastLoginTime" label="最后登录" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="form.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索
const searchQuery = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)

// 用户列表
const userList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: null,
  username: '',
  email: '',
  password: '',
  role: 'user',
  status: 1
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取用户列表
    // 这里模拟数据
    const mockData = Array.from({ length: 20 }, (_, index) => ({
      id: index + 1,
      username: `user${index + 1}`,
      email: `user${index + 1}@example.com`,
      avatar: `https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png`,
      role: index === 0 ? 'admin' : 'user',
      status: 1,
      registerTime: '2024-01-01 12:00:00',
      lastLoginTime: '2024-01-02 12:00:00'
    }))
    
    // 尝试从 localStorage 加载用户列表
    const savedUserList = localStorage.getItem('userList');
    if (savedUserList) {
      try {
        // 使用加载的数据，并确保每个用户都有必要的属性
        // 对加载的数据进行排序
        const loadedUserList = JSON.parse(savedUserList).map(user => ({
            avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png', // 添加默认头像以防丢失
            registerTime: '2024-01-01 12:00:00', // 添加默认注册时间
            lastLoginTime: '2024-01-02 12:00:00', // 添加默认最后登录时间
            ...user
        }));
        userList.value = loadedUserList.sort((a, b) => a.id - b.id); // 按ID排序
      } catch (e) {
        console.error('Failed to load user list from localStorage for stats:', e);
        userList.value = mockData.sort((a, b) => a.id - b.id); // 加载失败则使用模拟数据并排序
      }
    } else {
      userList.value = mockData.sort((a, b) => a.id - b.id); // 如果 localStorage 中没有数据，使用模拟数据并排序
    }

    // 模拟搜索
    let filteredData = userList.value // 对加载或模拟的数据进行搜索和分页
    if (searchQuery.value) {
      filteredData = userList.value.filter(user => 
        user.username.includes(searchQuery.value) ||
        user.email.includes(searchQuery.value)
      )
    }
    
    total.value = filteredData.length
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    userList.value = filteredData.slice(start, end) // 更新显示的用户列表为搜索和分页后的结果

  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUserList()
}

// 添加用户
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(form, {
    id: null,
    username: '',
    email: '',
    password: '',
    role: 'user',
    status: 1
  })
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    id: row.id,
    username: row.username,
    email: row.email,
    role: row.role,
    status: row.status
  })
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该用户吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    // TODO: 调用API删除用户
    const index = userList.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      userList.value.splice(index, 1)
      localStorage.setItem('userList', JSON.stringify(userList.value)); // 保存到 localStorage
      ElMessage.success('删除成功')
      // 重新获取并排序用户列表以更新显示
      fetchUserList();
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 修改用户状态
const handleStatusChange = async (row) => {
  try {
    // TODO: 调用API修改用户状态
    // 模拟更新 localStorage
    const index = userList.value.findIndex(item => item.id === row.id);
    if(index > -1) {
        userList.value[index].status = row.status;
        localStorage.setItem('userList', JSON.stringify(userList.value)); // 保存到 localStorage
        // 重新获取并排序用户列表以更新显示
        fetchUserList();
    }
    ElMessage.success(`用户状态修改成功`)
  } catch (error) {
    console.error('修改状态失败:', error)
    ElMessage.error('修改状态失败')
    row.status = row.status === 1 ? 0 : 1 // 恢复状态
  }
}

// 提交表单 (添加/编辑用户)
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    // TODO: 调用API保存用户
    if (dialogType.value === 'add') {
      // 模拟添加用户
      // 找到当前最大ID
      const maxId = userList.value.reduce((max, user) => Math.max(max, user.id), 0);
      const newId = maxId + 1;

      const newUser = {
        id: newId, // 使用计算出的新ID
        username: form.username,
        email: form.email,
        password: form.password, // 实际应用中密码不应该这样处理
        role: form.role,
        status: form.status,
        avatar: `https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png`, // 默认头像
        registerTime: new Date().toLocaleString(),
        lastLoginTime: new Date().toLocaleString()
      }
      // 添加新用户后对整个列表进行排序
      userList.value.push(newUser);
      userList.value.sort((a, b) => a.id - b.id);

    } else {
      // 模拟更新用户
      const index = userList.value.findIndex(user => user.id === form.id)
      if (index > -1) {
        Object.assign(userList.value[index], {
          username: form.username,
          email: form.email,
          // password: form.password, // 不直接更新密码
          role: form.role,
          status: form.status
        })
      }
    }

    localStorage.setItem('userList', JSON.stringify(userList.value)); // 保存到 localStorage
    dialogVisible.value = false
    ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')

    // 添加或更新后重新获取用户列表以更新显示（会包含排序逻辑）
    fetchUserList();

  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-manage {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-detail {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.email {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 